/*
 * @Description: 排序设置reducer
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2023-01-12 16:30:38
 */

import {
  ADD_SORTING,
  DELETE_SORTING,
  EDIT_SORTING,
  INIT_QUERY,
  INIT_TABLE,
  SET_QUERY,
  SET_SELECTED_ITEM,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL,
  SET_SORTING_LIST
} from '../constants';
import { jsonClone } from '@/utils';
import { concat } from 'lodash-es';

export const SortReducer = (state, action) => {
  switch (action.type) {
    // 设置选中的全宗
    case SET_SELECT_FOND:
      return {
        ...state,
        selectFond: action.data
      };

    // 设置选中的档案类型
    case SET_SELECT_AT:
      return {
        ...state,
        selectAT: action.data
      };

    // 设置选中的层级
    case SET_SELECT_LEVEL:
      return {
        ...state,
        selectLevel: action.data
      };

    // 加载表格数据及相关数据
    case INIT_QUERY: {
      return {
        ...state,
        listQuery: action.data
      };
    }

    // 加载表格数据及相关数据
    case SET_QUERY: {
      const listQuery = { ...state.listQuery };
      action.info.forEach(({ key, value }) => {
        listQuery[key] = value;
      });

      return {
        ...state,
        listQuery
      };
    }

    // 加载表格数据及相关数据
    case INIT_TABLE: {
      return {
        ...state,
        selectItems: []
      };
    }

    // 设置排序列表
    case SET_SORTING_LIST:
      return {
        ...state,
        list: action.data,
        loading: false
      };

    /**
     * @description: 保存表格选中的条目id
     * @param {number[]} data
     */
    case SET_SELECTED_ITEM:
      return { ...state, selectItems: action.data };

    /**
     * @description: 删除排序
     * @param {Array<number|string>} ids 删除排序的ID
     */
    case DELETE_SORTING: {
      const { ids } = action;
      const list = state.list.filter((item) => ids.indexOf(item.rule.id) < 0);
      return { ...state, list };
    }

    case EDIT_SORTING: {
      const { id, data } = action;
      const orgList = jsonClone(state.list);
      for (let i = 0; i < orgList.length; i++) {
        if (orgList[i].rule.id === id) {
          orgList.splice(i, 1, data);
        }
      }
      return { ...state, list: orgList };
    }

    // 增加排序规则
    case ADD_SORTING: {
      const { data } = action;
      return {
        ...state,
        list: concat(state.list, data),
        dialog: {
          fieldList: []
        }
      };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
